package com.nrgedge;

import info.magnolia.ui.workbench.column.AbstractColumnFormatter;
import info.magnolia.ui.workbench.column.PathColumnFormatter;
import info.magnolia.ui.workbench.column.definition.MetaDataColumnDefinition;

import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.RepositoryException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.ui.Table;

public class VanityUrlPathColumnFormatter  extends AbstractColumnFormatter<MetaDataColumnDefinition> {

	private static final long serialVersionUID = -5925780066826606759L;
	
	private static final Logger log = LoggerFactory.getLogger(PathColumnFormatter.class);

    public VanityUrlPathColumnFormatter(MetaDataColumnDefinition definition) {
        super(definition);
    }

    @Override
    public Object generateCell(Table source, Object itemId, Object columnId) {

        final Item jcrItem = getJcrItem(source, itemId);
        if (jcrItem != null) {
            try {
            	
            	String path = jcrItem.getPath();
            	
            	if (jcrItem.getDepth() > 4) {
            		return path.substring(PathHelper.nthLastIndexOf(path, '/', 3), path.length());
            	} else {
            		return path.substring(path.lastIndexOf('/'), path.length());	
            	}
            	
            } catch (RepositoryException re) {
                log.info("Failed to retrieve path for item '{}':", jcrItem.toString(), re);
            }
        }
        return null;

    }
    
}
